<script setup lang="ts">
import { tableConfig } from './config/table-config';
import baseTable from '@/components/base-ui/base-table/index.vue';
import { doAddAuxiliary } from '@/api/modeling/auxiliaryResources/index';
import { handleDelKey, checkRepeat, RepeatMsg } from '@/utils';
import usePageSave from '@/hooks/usePageSave';
import useEmit from '@/hooks/useEmitter';
import { message } from '@/components/q-message/message';
import type { AddAuxiliaryData } from '@/api/modeling/auxiliaryResources/model/type';

const { modalOk, modalSlotRef, loading } = useModal();

const STORE_KEY = 'auxiliaryResourcesAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听 EventBus

defineOptions({
    name: 'AuxiliaryResourcesAdd'
});

useRecordData(modalSlotRef, STORE_KEY, isUpdate, startRecording); // 复制辅助资源相关

/**
 * @: 新增提交
 */
const handleSubmit = async () => {
    const tableData: AddAuxiliaryData[] = modalSlotRef.value?.getSaveData();
    const value = tableData.map(item => handleDelKey(item, ['id']));
    const msg = checkRepeat(value, ['auxiliaryResourceCoding']);
    if (msg) {
        const { line, value } = msg;
        RepeatMsg({ line, value, label: '辅助资源编码' });
        return;
    }
    try {
        const res = await doAddAuxiliary(value);
        if (res) {
            message.success('新增成功！');
        }
        return res;
    } catch (error) {
        console.log(error);
    }
};

/**
 * @: 点击保存
 */
const handleOk = async () => {
    try {
        await modalOk(handleSubmit);
        usePageSave('/auxiliaryResources');
    } catch (e) {
        console.log(e);
    }
};
</script>
<template>
    <q-page>
        <base-table ref="modalSlotRef" :table-config="tableConfig" add-table-row open-sticky>
            <!-- 保存/取消 -->
            <template #tableHeadEnd>
                <q-submit-button
                    size="default"
                    :hide-label="true"
                    align="right"
                    :horizontal="true"
                    :loading="loading"
                    :cancel-button="false"
                    @save="handleOk"
                />
            </template>
        </base-table>
    </q-page>
</template>

<style lang="scss" scoped></style>
